package com.beyondsoft.common.core.constant;

import org.apache.commons.lang.math.RandomUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 事务状态管理
 */
public interface TransactionConstants {

    String PACKAGEKEY = "request.package.";

    int PACKAGEKEY_STATUS_INIT = 0;
    int PACKAGEKEY_STATUS_SUCCESS = 1;
    int PACKAGEKEY_STATUS_ERROE = 2;

    //事务锁
    Map<String, Long> transactionLock = new LinkedHashMap<>();
    //事务处理状态
    Map<String, Integer> transactionState = new LinkedHashMap<>();

    //设置事务状态
    static void setTransactionState(String key, Integer state) {
        transactionState.put(key, state);
    }

    //获取事务状态
    static Integer getTransactionState(String key) {
        if (transactionState.get(key) == null) {
            transactionState.put(key, PACKAGEKEY_STATUS_INIT);
        }
        return transactionState.get(key);
    }

    //清除事务状态
    static void clearTransactionState(String key) {
        transactionState.remove(key);
    }

    //获取锁
    static Long getTransactionLock(String key) {
        //第一遍初始化锁 锁生成规则:当前时间戳+ 6位随机数
        if (transactionLock.get(key) == null) transactionLock.put(key, new Date().getTime() + RandomUtils.nextInt(6));
        return transactionLock.get(key);
    }

    //清除锁
    static void clearTransactionLock(String key) {
        transactionLock.remove(key);
    }

}